/*
 * Created by: Peter Weissbrod
 * Created: Tuesday, January 22, 2008
 */
using System;
using System.Data.SqlTypes;
using PostSharp.Laos;
using PostSharp.UserSamples.Exceptions;
using PostSharp.UserSamples.Utils;

namespace PostSharp.UserSamples.Validators
{
    /// <summary>
    /// Throws a ValidationException if the DateTime parameter is outside of Sql Server's acceptable range of dates
    /// </summary>
    [Serializable]
    public class SqlDateTimeRangeValidator : OnMethodBoundaryAspect
    {
        /// <summary>
        /// Restricted to property setters of type DateTime
        /// </summary>
        /// <param name="method"></param>
        /// <returns></returns>
        public override bool CompileTimeValidate(System.Reflection.MethodBase method)
        {
            return CompileTimeValidateScenario.ValidateForPublicPropertySetter(method) &&
                   CompileTimeValidateScenario.RestrictPropertySetterToSpecificType(method, typeof (DateTime));
        }
        /// <summary>
        /// Throws an exception if anything is out of the range.
        /// </summary>
        /// <param name="eventArgs"></param>
        public override void OnEntry(MethodExecutionEventArgs eventArgs)
        {
            if (eventArgs.GetArguments() != null)
            {
                DateTime value = (DateTime) eventArgs.GetArguments()[0];
                if (value.CompareTo(SqlDateTime.MinValue) < 0)
                    throw new ValidationException(
                        "Scalar value [" + value + "] was below minimum [" + SqlDateTime.MinValue + "]",
                        eventArgs);
            }
            base.OnEntry(eventArgs);
        }
    }
}